package com.nail.controller;

import com.alibaba.druid.util.StringUtils;
import com.nail.api.customMake.bean.Indent;
import com.nail.api.customMake.service.IInDentService;
import com.nail.api.customMake.service.IPaypalService;
import com.nail.api.user.bean.User;
import com.nail.api.user.service.IUserService;
import com.nail.client.RedisClient;
import com.nail.common.Constant;
import com.nail.utils.IPUtils;
import com.nail.utils.Result4API;
import com.paypal.api.payments.Payment;
import com.paypal.base.rest.PayPalRESTException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/system")
public class SystemController {

	Logger logger = Logger.getLogger(this.getClass());

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Autowired
	private RedisClient redisClient;

	@Autowired
	private IUserService userService;

	@Autowired
	private IPaypalService paypalService;

	@Autowired
	private IInDentService inDentService;



	@PostMapping(value="/login")
	@ResponseBody
	public Result4API loginIn(HttpServletRequest request,String userName,String password){
		Result4API result = new Result4API();
		logger.info(sdf.format(new Date()) +" "+IPUtils.getRemoteHost(request) + ",用户访问了本接口：loginIn" );
		try {
			if(StringUtils.isEmpty(userName)|| StringUtils.isEmpty(password)){
				result.setCode(Constant.API_CODE_501);
				result.setMsg(Constant.API_MSG_501);
				return result;
			}

			Map<String,Object> map = userService.LoginIn(userName,password);
			if(map == null){
				result.setCode(Constant.API_CODE_504);
				result.setMsg(Constant.API_MSG_504);
				return result;
			}else{
				if(map.get("isAble") != null && map.get("isAble").toString().equals("0")){
					result.setCode(Constant.API_CODE_1002);
					result.setMsg(Constant.API_MSG_1002);
					return result;
				}
				result.setCode(200);
				result.setData(map);
				result.setMsg(Constant.API_MSG_SUCCESS);
				return result;
			}
		} catch (Exception e) {
			logger.error(e.toString());
			e.printStackTrace();
			result.setCode(Constant.API_CODE_ERROR);
			result.setMsg(Constant.API_MSG_ERROR);
			return result;
		}
	}

	@GetMapping(value="/logout")
	@ResponseBody
	public Result4API loginOut(HttpServletRequest request,String token){
		Result4API result = new Result4API();
		logger.info(sdf.format(new Date()) +" "+IPUtils.getRemoteHost(request) + ",用户访问了本接口：loginOut" );
		if(StringUtils.isEmpty(token)){
			result.setCode(Constant.API_CODE_501);
			result.setMsg(Constant.API_MSG_501);
			return result;
		}
		try {
			redisClient.remove(Constant.REDIS_USER_KEY+token);
			result.setCode(200);
			result.setMsg(Constant.API_MSG_SUCCESS);
			return result;
		} catch (Exception e) {
			logger.error(e.toString());
			e.printStackTrace();
			result.setCode(Constant.API_CODE_ERROR);
			result.setMsg(Constant.API_MSG_ERROR);
			return result;
		}
	}

	@PostMapping(value="/register")
	@ResponseBody
	public Result4API register(HttpServletRequest request,User user){
		Result4API result = new Result4API();
		logger.info(sdf.format(new Date()) +" "+ IPUtils.getRemoteHost(request) + ",用户访问了本接口：register" );
		if(user == null || StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword())
				|| StringUtils.isEmpty(user.getEmail()) || StringUtils.isEmpty(user.getCountry())){
			result.setCode(Constant.API_CODE_501);
			result.setMsg(Constant.API_MSG_501);
			return result;
		}

		try {
			Map<String,Object> map = userService.registerUser(user);
			if(map == null || map.get("error") != null){
				if(map.get("error") != null){
					result.setCode(Constant.API_CODE_ERROR);
					result.setMsg(map.get("error").toString());
					return result;
				}
				result.setCode(Constant.API_CODE_504);
				result.setMsg(Constant.API_MSG_504);
				return result;
			}else{
				result.setCode(200);
				result.setData(map);
				result.setMsg(Constant.API_MSG_SUCCESS);
				return result;
			}
		} catch (Exception e) {
			logger.error(e.toString());
			e.printStackTrace();
			result.setCode(Constant.API_CODE_ERROR);
			result.setMsg(Constant.API_MSG_ERROR);
			return result;
		}
	}

	@GetMapping(value="/userIsExist")
	@ResponseBody
	public Result4API isExist(HttpServletRequest request,String userName){
		Result4API result = new Result4API();
		logger.info(sdf.format(new Date()) +" "+ IPUtils.getRemoteHost(request) + ",用户访问了本接口：isExist" );
		if(StringUtils.isEmpty(userName)){
			result.setCode(Constant.API_CODE_501);
			result.setMsg(Constant.API_MSG_501);
			return result;
		}
		try {
			boolean isExist = userService.getUserIsExist(userName);
			result.setCode(200);
			result.setMsg(Constant.API_MSG_SUCCESS);
			result.setData(isExist);
			return result;
		} catch (Exception e) {
			logger.error(e.toString());
			e.printStackTrace();
			result.setCode(Constant.API_CODE_ERROR);
			result.setMsg(Constant.API_MSG_ERROR);
			return result;
		}
	}


	@GetMapping("/paySuccess")
	public String paySuccess(HttpServletRequest request,String paymentId,String PayerID,String orderIds,String payToken,String ltk){
		logger.info(sdf.format(new Date()) +" "+ IPUtils.getRemoteHost(request) + ",用户访问了本接口：paySuccess" );
		if( StringUtils.isEmpty(orderIds) || StringUtils.isEmpty(PayerID)  || StringUtils.isEmpty(paymentId) || StringUtils.isEmpty(payToken)){
			logger.info("支付缺少参数!");
			logger.info("paymentId:"+paymentId+" ===== PayerID:"+PayerID+" ====== orderIds:"+orderIds +" ====== payToken:"+payToken +" ====== ltk:"+ltk);
		}
		User user = (User)redisClient.get(Constant.REDIS_USER_KEY + ltk); 
		try {
			Payment payment = paypalService.executePayment(paymentId, PayerID);
			if(payment.getState().equals("approved")){       
				if(orderIds.contains(",")){
					for (String orderId : orderIds.split(orderIds)) {
						Indent indent = inDentService.getIndentById(user.getId(),orderId);
						//记录支付信息
						paypalService.setPayMessage(user,indent,paymentId,PayerID);
					} 
				}else{
					Indent indent = inDentService.getIndentById(user.getId(),orderIds);
					//记录支付信息
					paypalService.setPayMessage(user,indent,paymentId,PayerID);
				}				     
				//记录支付成功
				redisClient.set(payToken, "success",60*60L);
				logger.info("返回成功！支付成功!orderid:"+orderIds);
				logger.info("paymentId:"+paymentId+" ===== PayerID:"+PayerID+" ====== orderIds:"+orderIds +" ====== payToken:"+payToken +" ====== ltk:"+ltk);
			}else{
				//记录支付失败
				redisClient.set(payToken, "error",60*60L);
				logger.info("返回成功！支付失败!orderid:"+orderIds);
				logger.info("paymentId:"+paymentId+" ===== PayerID:"+PayerID+" ====== orderIds:"+orderIds +" ====== payToken:"+payToken +" ====== ltk:"+ltk);
			}			
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
			logger.info("支付失败!orderid:"+orderIds);
			logger.info("paymentId:"+paymentId+" ===== PayerID:"+PayerID+" ====== orderIds:"+orderIds +" ====== payToken:"+payToken +" ====== ltk:"+ltk);
			return "/error.html";
		}
		return "/success.html";
	}
}


